/*
 * Copyright 2002-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.servlet.mvc.annotation;

import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.WebUtils;

/**
 * Helper class for annotation-based request mapping.
 *
 * @author Juergen Hoeller
 * @author Arjen Poutsma
 * @author Rossen Stoyanchev
 * @since 2.5.2
 * @deprecated as of Spring 3.2, together with {@link DefaultAnnotationHandlerMapping},
 * {@link AnnotationMethodHandlerAdapter}, and {@link AnnotationMethodHandlerExceptionResolver}.
 */

/**
 * 基于注释的请求映射的工具类
 */
@Deprecated
abstract class ServletAnnotationMappingUtils {

	/**
	 * Check whether the given request matches the specified request methods.
	 * @param methods the HTTP request methods to check against
	 * @param request the current HTTP request to check
	 */
	/**
	 * 检验当前报文中的请求类型是否符合要求：
	 * 1、如果未给定要求的请求类型【methods为空】，则当前请求类型不能为options请求。
	 * 2、如果给定了要求的请求类型【methods不为空】，则当前请求类型必须包含在给定的请求类型中。
	 */
	public static boolean checkRequestMethod(RequestMethod[] methods, HttpServletRequest request) {
		//当前报文请求类型
		String inputMethod = request.getMethod();
		/** 1、如果给定的请求类型【methods】为空，并且当前请求不是options请求，则返回true */
		if (ObjectUtils.isEmpty(methods) && !RequestMethod.OPTIONS.name().equals(inputMethod)) {
			return true;
		}
		/** 2、如果当前请求类型包含在给定的请求类型中，则返回true */
		for (RequestMethod method : methods) {
			if (method.name().equals(inputMethod)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Check whether the given request matches the specified parameter conditions.
	 * @param params  the parameter conditions, following
	 * {@link org.springframework.web.bind.annotation.RequestMapping#params() RequestMapping.#params()}
	 * @param request the current HTTP request to check
	 */
	/**
	 * 检验当前报文中的请求参数是否符合要求：
	 * 1、如果给定了要求的请求参数【params不为空】
	 * 	  1.1、不包含"="
	 * 	  	  1.1.1、以"!"开头，则不能包含param.substring(1)、param.substring(1)+".x"、param.substring(1)+".y"参数
	 * 	  	  1.1.2、不以"!"开头，则需包含param.substring(1)或param.substring(1)+".x"或param.substring(1)+".y"参数
	 * 	  1.2、包含"="
	 * 	      1.2.1、包含"!="，则需满足key!=value
	 *   	  1.2.2、不包含"!="，则需满足key==value
	 * 2、如果未给定要求的请求参数【params为空】，则对报文请求参数不做要求。
	 */
	public static boolean checkParameters(String[] params, HttpServletRequest request) {
		//1、如果params不为空
		if (!ObjectUtils.isEmpty(params)) {
			for (String param : params) {
				//分离key value
				int separator = param.indexOf('=');
				//1.1、不包含"="
				if (separator == -1) {
					//1.1.1、以"!"开头
					if (param.startsWith("!")) {
						//包含参数名为"param"或"param.x"或"param.y"的参数
						if (WebUtils.hasSubmitParameter(request, param.substring(1))) {
							return false;
						}
					}
					//1.1.2、不以"!"开头且不包含参数名为"param"或"param.x"或"param.y"的参数
					else if (!WebUtils.hasSubmitParameter(request, param)) {
						return false;
					}
				}
				//1.2、包含"="
				else {
					//是否包含"!="
					boolean negated = separator > 0 && param.charAt(separator - 1) == '!';
					String key = !negated ? param.substring(0, separator) : param.substring(0, separator - 1);
					String value = param.substring(separator + 1);
					boolean match = value.equals(request.getParameter(key));
					//1.2.1、包含"!="，匹配结果取反
					if (negated) {
						match = !match;
					}
					if (!match) {
						return false;
					}
				}
			}
		}
		return true;
	}

	/**
	 * Check whether the given request matches the specified header conditions.
	 * @param headers the header conditions, following
	 * {@link org.springframework.web.bind.annotation.RequestMapping#headers() RequestMapping.headers()}
	 * @param request the current HTTP request to check
	 */
	public static boolean checkHeaders(String[] headers, HttpServletRequest request) {
		//如果headers不为空
		if (!ObjectUtils.isEmpty(headers)) {
			for (String header : headers) {
				//分离key value
				int separator = header.indexOf('=');
				//1.1、不包含"="
				if (separator == -1) {
					//1.1.1、以"!"开头
					if (header.startsWith("!")) {
						//当前报文header中包含给定的key
						if (request.getHeader(header.substring(1)) != null) {
							return false;
						}
					}
					//1.1.1、不以"!"开头，且当前报文header中不包含给定的key
					else if (request.getHeader(header) == null) {
						return false;
					}
				}
				//1.2、包含"="
				else {
					//是否包含"!="
					boolean negated = (separator > 0 && header.charAt(separator - 1) == '!');
					String key = !negated ? header.substring(0, separator) : header.substring(0, separator - 1);
					String value = header.substring(separator + 1);
					//1.2.1、是"Accept"或"Content-Type"
					if (isMediaTypeHeader(key)) {
						//解析报文header中对应给定header key的MediaType类型
						List<MediaType> requestMediaTypes = MediaType.parseMediaTypes(request.getHeader(key));
						//解析给定header中的MediaType类型
						List<MediaType> valueMediaTypes = MediaType.parseMediaTypes(value);
						boolean found = false;
						//若报文header与给定heander中存在相同的MediaType类型，则found = true，退出循环
						for (Iterator<MediaType> valIter = valueMediaTypes.iterator(); valIter.hasNext() && !found;) {
							MediaType valueMediaType = valIter.next();
							for (Iterator<MediaType> reqIter = requestMediaTypes.iterator();
									reqIter.hasNext() && !found;) {
								MediaType requestMediaType = reqIter.next();
								if (valueMediaType.includes(requestMediaType)) {
									found = true;
								}
							}

						}
						//包含"!="，匹配结果取反
						if (negated) {
							found = !found;
						}
						if (!found) {
							return false;
						}
					}
					//1.2.2、不是"Accept"或"Content-Type"
					else {
						//匹配规则为判断value是否相等
						boolean match = value.equals(request.getHeader(key));
						//包含"!="，匹配结果取反
						if (negated) {
							match = !match;
						}
						if (!match) {
							return false;
						}
					}
				}
			}
		}
		return true;
	}

	private static boolean isMediaTypeHeader(String headerName) {
		return ("Accept".equalsIgnoreCase(headerName) || "Content-Type".equalsIgnoreCase(headerName));
	}

}
